package com.atguigu.srb.core.controller.admin;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.core.pojo.entity.IntegralGrade;
import com.atguigu.srb.core.service.IntegralGradeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 积分等级表 Controller
 * @author gcq
 * @Create 2021-04-11
 */
@Api(tags = "积分等级管理")
@RestController
@RequestMapping("/admin/core/integralGrade")
public class AdminIntegralGradeController {

    @Autowired
    IntegralGradeService integralGradeService;

    /**
     * 查询所有积分等级列表
     * @return 积分列表
     */
    @ApiOperation("积分等级列表")
    @GetMapping("/list")
    public R list()
    {

        List<IntegralGrade> list = integralGradeService.list();
//        int i = 10 / 0; // 算术异常
        return R.ok().data("list", list).message("获取列表成功");
    }

    /**
     * 删除积分记录
     * @param id id
     * @return 删除是否成功
     */
    @ApiOperation(value = "根据Id删除积分记录", notes = "逻辑删除数据")
    @DeleteMapping("/remove/{id}")
    public R remove(
            @ApiParam(value = "数据Id", example = "1", required = true)
            @PathVariable Long id)
    {
        boolean result = integralGradeService.removeById(id);
        if(result)
        {
            return R.ok().message("删除成功");
        } else {
            return R.error().message("删除失败");
        }
    }

    /**
     * 保存积分等级对象
     * @param integralGrade
     * @return
     */
    @ApiOperation("新增积分等级")
    @PostMapping("/save")
    public R save(@RequestBody IntegralGrade integralGrade)
    {
//        if (integralGrade.getBorrowAmount() == null)
//        {
//            throw new BusinessException(ResponseEnum.BORROW_AMOUNT_NULL_ERROR);
//        }
        // 为空就是正常，不为空就抛出异常
        Assert.notNull(integralGrade.getBorrowAmount(), ResponseEnum.BORROW_AMOUNT_NULL_ERROR);
        boolean save = integralGradeService.save(integralGrade);
        return save ? R.ok().message("保存成功") : R.error().message("保存失败");
    }

    @ApiOperation("根据Id获取积分等级")
    @GetMapping("/get/{id}")
    public R getById(@ApiParam(value = "数据Id", required = true, example = "1") @PathVariable Long id)
    {
        IntegralGrade integralGrade = integralGradeService.getById(id);
        return integralGrade != null ? R.ok().data("record", integralGrade) : R.error().message("获取数据表达式错误");
    }

    @ApiOperation("更新积分等级")
    @PutMapping("/update")
    public R updateById(@ApiParam(value = "积分等级对象", required = true) @RequestBody IntegralGrade integralGrade)
    {
        return integralGradeService.updateById(integralGrade) ? R.ok().message("更新成功") : R.error().message("更新失败");
    }
}